<template>
  <div>
    <van-nav-bar
      title="修改信息"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form @submit="onReg">
      <van-field
        v-model="userinfo.username"
        name="username"
        label-width="50px"
        label="用户名"
        placeholder="请输入用户名"
        :rules="loginFormRules.username"
      />
      <van-field
        v-model="userinfo.phone"
        name="phone"
        label-width="50px"
        label="手机号"
        placeholder="请输入手机号"
        :rules="loginFormRules.phone"
      />
      <van-field
        v-model="userinfo.password"
        type="password"
        label-width="50px"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="loginFormRules.password"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userinfo: {
        username: "",
        password: "",
        phone: "",
      },
      loginFormRules: {
        //验证用户名是否合法
        username: [
          { required: true, message: "请输入用户名" },
        ],
        // 验证手机号是否合法
        phone: [
          { required: true, message: "请输入手机号码" },
          { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式错误！" },
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: "请输入密码" },
          {
            pattern:/^[0-9]{6,15}$/,message: "密码应在错误！"
          },
        ],
      },
    };
  },
  created() {
    this.getUserinfo();
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    async onReg() {
      const { data: res } = await this.$http.put("userinfo",{username:this.userinfo.username,password:this.userinfo.password,phone:this.userinfo.phone});
      if (res.status !== 200) return this.$message.fail("修改失败！");
      this.$message.success("修改成功");
      this.$router.push('/user');
    },
    async getUserinfo() {
      const { data: res } = await this.$http.get("user");
      if (res.status !== 200) return this.$message.fail("获取失败");
      this.userinfo = res.data;
    },
  },
};
</script>

<style>
</style>